package com.itheima.mp.controller;

import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.dto.UserQueryDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.dto.UserQueryDTO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation("新增用户接口")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userDTO) {
        //1.把DTO拷贝到PO当中(DTO是前端传来的，PO是后端数据库的JavaBean)
        //创建目标对象实例
        User user = new User();
        //拷贝属性（源对象，目标对象）
        BeanUtils.copyProperties(userDTO, user);
        userService.save(user);
    }

    @ApiOperation("删除用户接口")
    @DeleteMapping("{id}")
    public void deleteUserById(@ApiParam("用户id") @PathVariable("id") Long id) {
        userService.removeById(id);
    }

    @ApiOperation("根据id查询用户接口")
    @GetMapping("{id}")
    public UserVO queryUserById(@ApiParam("用户id") @PathVariable("id") Long id) {
        //1.查询用户PO(这是数据库里面的实体类)
        User user = userService.getById(id);
        //2.把PO拷贝到VO(这是后端给前端返回的实体类)
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @ApiOperation("根据id批量查询接口")
    @GetMapping
    public List<UserVO> queryUserById(@ApiParam("用户id集合") @PathVariable("ids") List<Long> ids) {
        //1.查询用户PO集合(这是数据库里面的实体类)
        List<User> users = userService.listByIds(ids);
        //2.把PO集合拷贝到VO集合(这是后端给前端返回的实体类)
        List<UserVO> userVO = (List<UserVO>) new UserVO();
        BeanUtils.copyProperties(users, userVO);
        return userVO;
    }

    @ApiOperation("根据id扣减用户余额接口")
    @PutMapping("{id}/deduction/{money}")
    public void deductMoneyById(@ApiParam("用户id") @PathVariable("id") Long id,
                                @ApiParam("扣减的金额") @PathVariable("money") Integer money) {
        //这个需求的业务比较繁琐，还是得按照以前一样去自定义方法，mybatis-plus中提供的方法不足实现功能
        userService.deductBalance(id,money);
    }

    @ApiOperation("根据复杂条件查询用户接口")
    @GetMapping("/list")
    public List<UserVO> queryUsers(UserQueryDTO query) {
        List<User> users = userService.queryUsers(query.getName(),query.getStatus(),query.getMinBalance(),query.getMaxBalance());
        List<UserVO> userVO = (List<UserVO>) new UserVO();
        BeanUtils.copyProperties(users, userVO);
        return userVO;
    }

}
